package cn.com.dycc.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.com.dycc.pagepermission.htmlpermis.dao.HtmlDao;
import cn.com.dycc.sys_manage.usersysmanagement.service.UserService;

public class HtmlFilter implements Filter{

//	ServletContext context;
	private UserService userService;
	private HtmlDao htmlDao;

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		//禁用缓存
		response.setHeader("Cache-Control","no-cache"); 
		response.setHeader("Pragma","no-cache"); 
		response.setDateHeader("Expires",0); 
		
		//获取请求文件名：
		String uri = request.getRequestURI();
//		System.out.println("htmluri="+uri);
		int n = uri.indexOf(".");
//		System.out.println("n="+n);
		if(n<0){
			HttpSession session = request.getSession();
			session.setMaxInactiveInterval(30*60);
			
			String userId = (String) session.getAttribute("id");
			if(userId==null){
				//System.out.println("login1");
				response.sendRedirect("/login.html");
				return;
				
			}else{
//					System.out.println("else1");
				response.sendRedirect("/index.html");
				return;
			}				
		}
		String path = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
		System.out.println("htmlpath="+path);
		if("/login".equals(path)){
//			System.out.println("login="+path);
			chain.doFilter(request, response);
			return;
		}	
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(3*60);
		
		String userId = (String) session.getAttribute("id");
		if(userId==null){
			String agent = request.getHeader("user-agent");
			System.out.println("ag"+agent);
			if(agent.contains("okhttp/3.6.0")||agent.contains("Android")
					||agent.contains("iPhone")
					||agent.contains("iPad")
					){
				String account = request.getHeader("ac");
				String password = request.getHeader("pd");
				System.out.println("ah="+account+"p="+password);
				try {
					boolean b = userService.autoLogin(account, password, request);
					
					if(b){
						chain.doFilter(request, response);
						return;
					}
				} catch (Exception e) {
					return;
					// TODO: handle exception
				}		
			}else if(agent.contains("mui")){
				String str[] = agent.split(";");
				String accounts[] = str[1].split("=");
				String password = str[2].substring(2);
				String account = accounts[1];
				System.out.println("ah2="+account+"p="+password);
				try {
					boolean b = userService.autoLogin(account, password, request);
					
					if(b){
						chain.doFilter(request, response);
						return;
					}
				} catch (Exception e) {
					return;
					// TODO: handle exception
				}	
			}
//				System.out.println("login");
			response.sendRedirect("/login.html");
			
		}
//		else{
////			System.out.println("html-do");
////			System.out.println("注入="+roleDao);
////			System.out.println("rol="+request.getSession().getAttribute("id").toString());
////			//登录人所拥有能登录的菜单页面权限url
////			List<String> list_menu_url = roleDao.sysProgram("0");
////			System.out.println("list_menu_url="+list_menu_url);\
//			
//			//放行html
//			String open_html = PropertiesUtil.readProperties("conf/openHtml.properties","open_html");
//			String[] arr_open_html = open_html.split(",");
//			for(String ot : arr_open_html){
////				System.out.println("ot="+ot);
//				if(uri.equals(ot)){
//					chain.doFilter(request, response);
//					return;
//				}
//			}
////			
//			
////			System.out.println("o="+open_html);
////			System.out.println("9999");
////			if(uri.equals("/index.html")){
////				chain.doFilter(request, response);
////				return;
////			}else if(uri.equals("/right.html")){
////				chain.doFilter(request, response);
////				return;
////			}else if(uri.equals("/404.html")){
////				chain.doFilter(request, response);
////				return;
////			}else if(uri.equals("/error.html")){
////				chain.doFilter(request, response);
////				return;
////			}
//			
//			String org_id = request.getSession().getAttribute("org_id").toString();
//			HtmlParam htmlParam = new HtmlParam();
//			htmlParam.setLimit_flag(1);
//			htmlParam.setMenu_path(uri);
////			htmlParam.setOrg_id(org_id);
//			
//			System.out.println("htmlParam="+htmlParam);
//			
//			List<String> list_role = htmlDao.findMenuPath(htmlParam);
////			System.out.println("list_role="+list_role);
//			
//			String list_role2 = request.getSession().getAttribute("role_no").toString();
////			System.out.println("list_role2="+list_role2);
//			
//			String[] arr_role = list_role2.replace("[","").replace("]","").split(",");
////			System.out.println("arr_role="+Arrays.toString(arr_role));
//
//			for(String role : list_role){
//				role = (role==null)?"":role;
////				System.out.println("r="+role);
//				for(String role1 : arr_role){
////					System.out.println("r1="+role1);
//					if(role1.trim().equals(role.trim())){
////						request.setAttribute("uri",uri);
////						System.out.println("0.....");
//						chain.doFilter(request, response);
//						return;
//					}
//				}
//				
//			}
//			response.sendRedirect("/error.html");
			chain.doFilter(request, response);
//		}
		
		
		
	}

	public void init(FilterConfig arg0) throws ServletException {
        
		//XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(ac);
		String[]conf={"conf/spring-mvc.xml","conf/spring-mybatis.xml"};
		ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
//		if(ac!=null&&ac.getBean("roleDao")!=null && roleDao==null){
//			roleDao = (RoleDao) ac.getBean("roleDao");
//		}
		if(ac!=null&&ac.getBean("htmlDao")!=null && htmlDao==null){
			htmlDao = (HtmlDao) ac.getBean("htmlDao");
		}
//		if(ac!=null&&ac.getBean("roleUserDao")!=null && roleUserDao==null){
//			roleUserDao = (RoleUserDao) ac.getBean("roleUserDao");
//		}
		if(ac!=null&&ac.getBean("userService")!=null&&userService==null){
			userService = (UserService) ac.getBean("userService");
		}
	}
}
